package other.her.system.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.rkhd.platform.sdk.common.OauthConfig;
import com.rkhd.platform.sdk.exception.ApiEntityServiceException;
import com.rkhd.platform.sdk.http.*;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.model.BatchOperateResult;
import com.rkhd.platform.sdk.model.OperateResult;
import com.rkhd.platform.sdk.model.QueryResult;
import com.rkhd.platform.sdk.model.XObject;
import com.rkhd.platform.sdk.service.CacheService;
import com.rkhd.platform.sdk.service.XObjectService;
import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.*;

/**
 * ClassName: HCXObjectService
 * Description: 封装销售易XObjectService
 * date: 2023/5/29
 *
 * @author Arende
 */
public class HCXObjectService {

    private static final Logger logger = LoggerFactory.getLogger();

    private static final XObjectService xObjectService = XObjectService.instance();

    private static final ValueFilter VALUE_FILTER = new DecimalValueFilter();

    public static boolean isLocal = false;

    /**
     * 根据查询语句获取系统记录。仅支持单表查询。（最大获取1条记录）
     * <p>
     * 默认以管理员权限查询
     *
     * @param sql
     * @param <T>
     * @return
     */
    public static <T extends XObject> T queryOne(String sql) {
        return queryOne(sql, true);
    }

    /**
     * 根据查询语句获取系统记录。仅支持单表查询。（最大获取1条记录）
     *
     * @param sql
     * @param <T>
     * @return
     */
    public static <T extends XObject> T queryOne(String sql, Boolean admin) {
        StringBuilder sqlBuilder = new StringBuilder(sql);
        sqlBuilder.append(" limit 0,1");
        logger.debug("queryOne sql:" + sqlBuilder);
        try {
            QueryResult<XObject> result = xObjectService.query(sqlBuilder.toString(), admin);
            if (!result.getSuccess()) {
                logger.info("queryOne fail message:" + result.getErrorMessage());
                return null;
            }
            if (null == result.getRecords() || result.getRecords().size() == 0) {
                return null;
            }
            return (T) result.getRecords().get(0);
        } catch (ApiEntityServiceException e) {
            logger.error("queryOne error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 递归查询所有记录(每次查询100条记录)
     *
     * @param sql
     * @param <T> 注：平台最高限制300条
     * @return
     */
    public static <T extends XObject> List<T> queryAll(String sql) {
        HCXObjectService service = new HCXObjectService();
        List<T> list = new ArrayList<T>();
        List<T> resultList = service.getMaxQuery(list, sql, 0L, 100L);
        return resultList;
    }

    /**
     * 获取记录总数
     *
     * @param sql
     * @return
     */
    public static Long getCount(String sql) {
        logger.debug("Sql:" + sql);
        try {
            QueryResult<XObject> result = xObjectService.query(sql, true);
            if (!result.getSuccess()) {
                logger.info("getCount:" + result.getErrorMessage());
                return -1L;
            }
            return result.getTotalCount();
        } catch (Exception e) {
            logger.error("getCount error:" + e.getMessage());
            return -1L;
        }
    }

    /**
     * 获取单条记录
     *
     * @param xObject
     * @param <T>
     * @return
     */
    public static <T extends XObject> T get(T xObject) {
        try {
            return xObjectService.get(xObject, true);
        } catch (ApiEntityServiceException e) {
            logger.error("获取单条记录异常, error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 根据id获取对象信息
     *
     * @param apiKey
     * @param id
     * @param <T>
     * @return
     */
    public static <T extends XObject> T getById(String apiKey, Long id) {
        HCXObjectService service = new HCXObjectService();
        return service.getById(apiKey, id, true);
    }

    /**
     * 根据id获取对象信息
     *
     * @param apiKey
     * @param id
     * @param admin
     * @param <T>
     * @return
     */
    public <T extends XObject> T getById(String apiKey, Long id, Boolean admin) {
        try {
            if (id == null) {
                logger.info("id can not be nulls");
                return null;
            } else {
                RkhdHttpData data = RkhdHttpData.newBuilder().callString("/rest/data/v2.0/xobjects/" + apiKey + "/" + id).callType("GET").header("xsy-criteria", admin ? "10" : "").build();
                JSONObject jsonObject = RkhdHttpClient.instance().execute(data, JSON::parseObject);
                createLog(data, jsonObject.toString());
                checkResult(jsonObject);
                JSONObject jsonModle = jsonObject.getJSONObject("data");
                if (jsonModle == null) {
                    logger.info("result is null");
                    return null;
                } else {
                    T resultXobject = convertJsonToXobject(jsonModle, apiKey);
                    return resultXobject;
                }
            }
        } catch (Exception e) {
            logger.error("get " + apiKey + " by id error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 新增(默认管理员权限)
     *
     * @param xObject
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult insert(T xObject) {
        return insert(xObject, true);
    }

    /**
     * 修改(默认管理员权限)
     *
     * @param xObject
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult update(T xObject) {
        return update(xObject, true);
    }

    /**
     * 批量新增(默认管理员权限)
     *
     * @param xObjects
     * @param <T>
     * @return
     */
    public static <T extends XObject> BatchOperateResult insertBatch(List<T> xObjects) {
        if (xObjects != null && xObjects.size() > 0) {
            return insertBatch(xObjects, true);
        }
        return null;
    }

    /**
     * 批量修改(默认管理员权限)
     *
     * @param xObjects
     * @param <T>
     * @return
     */
    public static <T extends XObject> BatchOperateResult updateBatch(List<T> xObjects) {
        if (xObjects != null && xObjects.size() > 0) {
            return updateBatch(xObjects, true);
        }
        return null;
    }

    /**
     * 删除
     *
     * @param XObject
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult delete(T XObject) {
        try {
            return xObjectService.delete(XObject, true);
        } catch (Exception e) {
            logger.error("记录删除失败, error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 批量删除
     *
     * @param XObjects
     * @param <T>
     * @return
     */
    public static <T extends XObject> BatchOperateResult deleteBatch(List<T> XObjects) {
        if (XObjects == null || XObjects.size() <= 0) {
            return null;
        }
        try {
            if (isLocal) {
                for (T xObject : XObjects) {
                    xObjectService.delete(xObject);
                }
                return null;
            } else {
                return xObjectService.delete(XObjects, true);
            }
        } catch (Exception e) {
            logger.error("批量删除失败, error:" + e.getMessage());
            return null;
        }
    }


    /**
     * 加锁或解锁
     *
     * @param XObject
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult lockOrUnLock(T XObject, Boolean lock) {
        OperateResult result = null;
        try {
            if (lock) {
                result = xObjectService.lock(XObject, true);
            } else {
                result = xObjectService.unlock(XObject, true);
            }
            return result;
        } catch (Exception e) {
            logger.error("记录删除失败, error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 转移
     *
     * @param xObject
     * @param targetUserId 被转移人的 UserId
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult transfer(T xObject, Long targetUserId) {
        try {
            return xObjectService.transfer(xObject, targetUserId, true);
        } catch (Exception e) {
            logger.error("批量删除失败, error:" + e.getMessage());
            return null;
        }
    }

    /**
     * 新增
     *
     * @param xObject
     * @param admin   是否管理员权限执行
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult insert(T xObject, Boolean admin) {
        OperateResult result = null;
        try {
            result = xObjectService.insert(xObject, admin);
        } catch (ApiEntityServiceException e) {
            logger.error("新增失败, error:" + e.getMessage());
        }
        return result;
    }

    /**
     * 修改
     *
     * @param xObject
     * @param admin   是否管理员权限执行
     * @param <T>
     * @return
     */
    public static <T extends XObject> OperateResult update(T xObject, Boolean admin) {
        OperateResult result = null;
        try {
            result = xObjectService.update(xObject, admin);
        } catch (ApiEntityServiceException e) {
            logger.error("修改失败, error:" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量新增
     *
     * @param xObjects
     * @param admin    是否管理员权限执行
     * @param <T>
     * @return
     */
    public static <T extends XObject> BatchOperateResult insertBatch(List<T> xObjects, Boolean admin) {
        BatchOperateResult result = null;
        try {
            if (isLocal) {
                for (T xObject : xObjects) {
                    xObjectService.insert(xObject);
                }
            } else {
                result = xObjectService.insert(xObjects, true);
            }
        } catch (ApiEntityServiceException e) {
            logger.error("批量新增失败, error:" + e.getMessage());
        }
        return result;
    }

    /**
     * 批量修改
     *
     * @param xObjects
     * @param admin    是否管理员权限执行
     * @param <T>
     * @return
     */
    public static <T extends XObject> BatchOperateResult updateBatch(List<T> xObjects, Boolean admin) {
        BatchOperateResult result = null;
        try {
            if (isLocal) {
                for (T xObject : xObjects) {
                    xObjectService.update(xObject);
                }
            } else {
                result = xObjectService.update(xObjects, true);
            }
        } catch (ApiEntityServiceException e) {
            logger.error("批量修改失败, error:" + e.getMessage());
        }
        return result;
    }

    /**
     * 递归查询最多totalSize条记录
     *
     * @param list
     * @param sql
     * @param startIndex
     * @param pageSize
     * @param <T>
     * @return
     */
    private <T extends XObject> List<T> getMaxQuery(List<T> list, String sql, Long startIndex, Long pageSize) {
        StringBuilder sqlBuilder = new StringBuilder(sql);
        sqlBuilder.append(" LIMIT ");
        sqlBuilder.append(startIndex);
        sqlBuilder.append(",");
        sqlBuilder.append(pageSize);
        logger.debug("getMaxQuery sql:" + sqlBuilder);
        try {
            QueryResult<XObject> queryResult = xObjectService.query(sqlBuilder.toString(), true);
            if (!queryResult.getSuccess()) {
                logger.info("getMaxQuery fail message: " + queryResult.getErrorMessage());
            }
            int size = queryResult.getRecords().size();
            if (queryResult.getSuccess() && size > 0) {
                list.addAll((List<T>) queryResult.getRecords());
            }
            if (size >= pageSize) {
                getMaxQuery(list, sql, startIndex + pageSize, pageSize);
            }
        } catch (Exception e) {
            logger.error("getMaxQuery error: " + e);
        }
        return list;
    }

    private void createLog(RkhdHttpData data, String result) {
        StringBuilder sb = new StringBuilder();
        sb.append("request: [").append(data.toString()).append("]").append(", response: ").append(result);
        logger.info(sb.toString());
    }

    private void checkResult(JSONObject result) throws ApiEntityServiceException {
        if (result.getLong("code") != 200L) {
            throw new ApiEntityServiceException(result.getString("msg"), result.getLong("code"));
        }
    }

    private <T extends XObject> T convertJsonToXobject(JSONObject json, String apiKey) throws Exception {
        String className = "com.rkhd.platform.sdk.data.model." + apiKey.substring(0, 1).toUpperCase() + apiKey.substring(1);
        Class clazz = Class.forName(className);
        T xObject = (T) JSON.parseObject(JSON.toJSONString(json, VALUE_FILTER, new SerializerFeature[0]), clazz);
        this.clearUpdateProperties(xObject);
        return xObject;
    }

    private <T extends XObject> void clearUpdateProperties(T xObject) throws Exception {
        Method clearMethod = XObject.class.getDeclaredMethod("_clearUpdateProperties");
        clearMethod.setAccessible(true);
        clearMethod.invoke(xObject);
    }

    private static class DecimalValueFilter implements ValueFilter {
        private DecimalValueFilter() {
        }

        public Object process(Object object, String name, Object value) {
            return !(value instanceof BigDecimal) && !(value instanceof Double) && !(value instanceof Float) ? value : new BigDecimal(value.toString());
        }
    }

//===============================================XOQL查询==============================================================//
//注：XOQL 在查询数据时会存在 3 秒以上的数据延时，对新增或发生变更的数据在 3 秒后才能通过 XOQL 查询到 ( 大规模数据操作时可能超过 3 秒)。
// 建议实时性不高的查询使用

    /**
     * 通过xoql查询出所有的结果（不受平台100条限制）
     *
     * @param
     * @param
     * @return 查询结果
     * @throws ApiEntityServiceException
     */
    public static JSONArray queryAllUseXoql(String xoql) {
        return queryAllUseXoql(xoql, false);
    }

    public static JSONArray queryAllUseXoql(String xoql, Boolean admin) {
        JSONArray arrays = new JSONArray();
        if (admin) {
            getAllDatasUseXoqlAdmin(arrays, xoql, 0L, 3000L);
        } else {
            getAllDatasUseXoql(arrays, xoql, 0L, 3000L);
        }
        return arrays;
    }

    /**
     * 通过xoql查询出所有的结果（不受平台100条限制）
     *
     * @param datas      返回参数
     * @param sql
     * @param startIndex
     * @param pageSize
     */
    private static void getAllDatasUseXoql(JSONArray datas, String sql, Long startIndex, Long pageSize) {
        StringBuilder sqlBulder = new StringBuilder(sql);
        sqlBulder.append(" LIMIT ");
        sqlBulder.append(pageSize);
        sqlBulder.append(" OFFSET ");
        sqlBulder.append(startIndex);

        logger.info("query all xoql:" + sqlBulder.toString());
        RkhdHttpData data = new RkhdHttpData();
        data.setCall_type("POST");
        data.setCallString("/rest/data/v2.0/query/xoql");
        data.putFormData("xoql", sqlBulder.toString());
        data.putFormData("useSimpleCode", true);

        try {
            String response = RkhdHttpClient.instance().performRequest(data);
            JSONObject json = JSONObject.parseObject(response);
            String code = json.getString("code");
            if (!"200".equals(code)) {
                return;
            }
            JSONObject json2 = json.getJSONObject("data");
            Long count = json2.getLong("count");
            datas.addAll(json2.getJSONArray("records"));
            if (Long.compare(count, pageSize) != -1) {
                getAllDatasUseXoql(datas, sql, startIndex + pageSize, pageSize);
            }
        } catch (Exception e) {
            logger.error("query all by xoal error:" + e.getMessage());
        }
    }

    /**
     * 以管理员身份查询
     *
     * @param datas
     * @param sql
     * @param startIndex
     * @param pageSize
     */
    private static void getAllDatasUseXoqlAdmin(JSONArray datas, String sql, Long startIndex, Long pageSize) {
        StringBuilder sqlBuilder = new StringBuilder(sql);
        sqlBuilder.append(" LIMIT ");
        sqlBuilder.append(pageSize);
        sqlBuilder.append(" OFFSET ");
        sqlBuilder.append(startIndex);

        RkhdHttpData data = new RkhdHttpData();
        data.setCall_type("POST");
        data.setCallString("/rest/data/v2.0/query/xoql");
        data.putFormData("xoql", sqlBuilder.toString());
        data.putFormData("useSimpleCode", true);
        data.putHeader("xsy-criteria", "10");

        OauthConfig config = new OauthConfig();
        CommonData commonData = new CommonData();
        commonData.setCallString(config.getDomain() + "/rest/data/v2.0/query/xoql");
        commonData.setCall_type("POST");
        commonData.putFormData("xoql", sqlBuilder.toString());
        commonData.putFormData("useSimpleCode", true);

        try {
            String accessToken = CacheService.instance().get("admin_access_token");
            if (StringUtils.isBlank(accessToken)) {
                logger.debug("调用授权接口获取access_token");
                accessToken = AdminOauthConfig.constructorImpl();
                CacheService.instance().set("admin_access_token", accessToken);
            }
            commonData.putHeader("Authorization", "Bearer " + accessToken);
            String response = CommonHttpClient.instance().performRequest(commonData);
            JSONObject json = JSONObject.parseObject(response);
            String code = json.getString("code");
            if (!"200".equals(code)) {
                if ("1020008".equals(code) && "无效的access token".equals(json.get("msg"))) {
                    logger.debug("无效的access token,重置admin_access_token");
                    CacheService.instance().set("admin_access_token", "");
                    getAllDatasUseXoqlAdmin(datas, sql, startIndex + pageSize, pageSize);
                }
                return;
            }
            JSONObject json2 = json.getJSONObject("data");
            Long count = json2.getLong("count");
            datas.addAll(json2.getJSONArray("records"));
            if (Long.compare(count, pageSize) != -1) {
                getAllDatasUseXoqlAdmin(datas, sql, startIndex + pageSize, pageSize);
            }
        } catch (Exception e) {
            logger.info("getAllDatasForXoql 发生异常" + e.getMessage());
        }
    }

    static class AdminOauthConfig {
        private String userName = "";
        private String password = "";
        private String securityCode = "";

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getSecurityCode() {
            return securityCode;
        }

        public void setSecurityCode(String securityCode) {
            this.securityCode = securityCode;
        }

        public static String constructorImpl() {
            CommonHttpClient client = CommonHttpClient.instance();
            AdminOauthConfig adminOauthConfig = new AdminOauthConfig();
            String userName = adminOauthConfig.getUserName();
            String password = adminOauthConfig.getPassword();
            String securityCode = adminOauthConfig.getSecurityCode();
            if (StringUtils.isBlank(userName) || StringUtils.isBlank(password) || StringUtils.isBlank(securityCode)) {
                logger.info("can not get admin config，please check you admin config");
                return "";
            }
            OauthConfig oauthConfig = new OauthConfig();
            String clientId = oauthConfig.getClientId();
            String clientSecret = oauthConfig.getClientSecret();
            client.setContentEncoding("UTF-8");
            client.setContentType("application/json");
            String oauthUrl = oauthConfig.getOauthUrl() + "?grant_type=password" + "&client_id=" + clientId + "&client_secret=" + clientSecret + "&username=" + userName + "&password=" + password + securityCode;
            CommonData commonData = new CommonData();
            commonData.setCall_type("GET");
            commonData.setCallString(oauthUrl);
            HttpResult result = client.execute(commonData);
            if (result != null && StringUtils.isNotBlank(result.getResult())) {
                JSONObject jsonObject = JSONObject.parseObject(result.getResult());
                if (jsonObject.containsKey("access_token")) {
                    return jsonObject.getString("access_token");
                } else {
                    if (jsonObject.containsKey("error_description")) {
                        logger.error(jsonObject.getString("error_description"));
                    } else {
                        logger.error(jsonObject.toString());
                    }
                }
            } else {
                logger.error("can not get the accessToken,please check your config");
            }
            return "";
        }
    }

    /**
     * 拆分集合
     *
     * @param <T>     泛型对象
     * @param resList 需要拆分的集合
     * @return 返回拆分后的各个集合组成的列表
     * 代码里面用到了guava和common的结合工具类
     **/
    public static <T> List<List<T>> splitList(List<T> resList, int subListLength) {
        if (resList.size() <= 0 || subListLength <= 0) {
            return new ArrayList<>();
        }
        List<List<T>> ret = new ArrayList<>();
        int size = resList.size();
        if (size <= subListLength) {
            // 数据量不足 subListLength 指定的大小
            ret.add(resList);
        } else {
            int pre = size / subListLength;
            int last = size % subListLength;
            // 前面pre个集合，每个大小都是 subListLength 个元素
            for (int i = 0; i < pre; i++) {
                List<T> itemList = new ArrayList<>();
                for (int j = 0; j < subListLength; j++) {
                    itemList.add(resList.get(i * subListLength + j));
                }
                ret.add(itemList);
            }
            // last的进行处理
            if (last > 0) {
                List<T> itemList = new ArrayList<>();
                for (int i = 0; i < last; i++) {
                    itemList.add(resList.get(pre * subListLength + i));
                }
                ret.add(itemList);
            }
        }
        return ret;
    }
}
